﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using PhotgalleryEntities;
using PhotoGalleryEnteties;
using PhotogalleryModel;
using photogalleryMVC.Filters;
using photogalleryMVC.Models.PhotoModels;

namespace photogalleryMVC.Controllers
{
    public class PhotoController : PhotoGalleryController 
    {
       
       

        // Get: {Thumbnail|Original|Optimized}/5
        public FilestreamResult GetPhoto(int id ,PhotoType photoType )
        {
            IStorageResult result=null;
            PhotoInfo photo = PhotoRepository.GetPhotoInfo(id); 
            //ADD:validation message for non existent id

            switch (photoType )
            {
                case PhotoType.OriginalImage:
                    result = PhotoRepository.GetOriginalPhoto(photo);
                    break;
                case PhotoType.ImageThumbnail :
                    result = PhotoRepository.GetPhotoThumbnail(photo);
                    break;
                case PhotoType.OptimizedImage :
                    result = PhotoRepository.GetOptimizedPhoto(photo);
                    break;
            }



            return new  FilestreamResult(result, @"image/" + photo.Format);
           
        }

        //
        // GET: /AddPhotoInAlbum/id
        
        [Authorize ]
        [AccessToResource( "albumId",ResourceType.Album )]
        public ActionResult AddPhoto(int albumId)
        {
            if (Request.IsAjaxRequest())
                return View("AddPhotoPartial");
            return View();
        } 
        
        //
        // POST: /AddPhotoInAlbum/id

        [HttpPost]
        [AccessToResource("albumId",ResourceType.Album  )]
        public ActionResult AddPhoto(HttpPostedFileBase image,int albumId)
        {
            if(image==null)
            {
                ModelState.AddModelError("", "File wasn`t selected");
                return View();
            }
            
            Album album = AlbumRepository.GetAlbumById(albumId);
           
            //check whether content -type is image 
            if(!image.ContentType.StartsWith( "image"))
            {
                ModelState.AddModelError("", "Loaded file should be image");
            }
            
            try
            {
                Bitmap bitmap = new Bitmap(image.InputStream);
                PhotoInfo photo = PhotoRepository.CreatePhoto(bitmap );
                UpdateModel(photo);
                photo.Album = AlbumRepository.GetAlbumById(albumId);
                //Validate photo 
                PhotoRepository.ValidatePhoto(photo).RegisterErrors(ModelState);    
                if(ModelState .IsValid )
                {

                    ModelContext.SaveChanges();
                    
                    PhotoRepository.SetPhoto(photo,bitmap );

                    return RedirectToAction("Detail",new {id=photo.PhotoId });
                }


                return (View());
            }
            catch(Exception exception )
            {
                return View();
            }
        }
        

        //
        // GET: /Photo/Detail/id
        [UpdateSubscribe("id")]
        public ActionResult Detail(int id)
        {
            PhotoInfo photo = PhotoRepository.GetPhotoInfo(id);
         

            Dictionary<int, string> hierarchy = new Dictionary<int, string>();
            hierarchy.Add(photo.Album.AlbumId, photo.Album.Title);
            Album parentAlbum = photo.Album.ParentAlbum;
            while (parentAlbum !=null)
            {
                hierarchy.Add(parentAlbum.AlbumId, parentAlbum.Title);
                parentAlbum = parentAlbum.ParentAlbum;
            }
            ViewData["hierarchy"] = hierarchy;
            ViewData["IsAuthenticated"] = User.Identity.IsAuthenticated;
            
            return View(photo);
        }




        //
        // GET: /Photo/Delete/5
 
        [Authorize ]
        [AccessToResource( "id",ResourceType.Photo )]
        public ActionResult Delete(int id)
        {
           
            PhotoInfo photo = PhotoRepository.GetPhotoInfo(id);
            int albumId = photo.Album.AlbumId;
            PhotoRepository.DeletePhoto(id);
            PhotoRepository.DeletePhoto(photo);
            ModelContext.SaveChanges();
            return RedirectToAction("Details", "Album", new {id=albumId  });
        }


        public ActionResult Last()
        {
            int numOfLastPhotos;
            numOfLastPhotos = (int.TryParse(WebConfigurationManager.AppSettings["lastQuantity"], out numOfLastPhotos))
                                  ? numOfLastPhotos
                                  : 5;
            return View(PhotoRepository.GetLastPhotos(numOfLastPhotos));

        }


    }


    
}
